﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using StartupTaskRunner.Logging;

namespace StartupTaskRunner
{
    static class ZipHelper
    {
        public static void ExtractArchiveToFileSystem(Stream stream, string targetPath, bool overwrite)
        {
            ZipFile archive = null;

            try
            {
                archive = new ZipFile(stream);

                foreach (ZipEntry entry in archive)
                {
                    string name = entry.Name;

                    name = name.Replace('/', '\\').TrimEnd('\\');
                    string fullZipToPath = Path.Combine(targetPath, name);
                    string directoryName = Path.GetDirectoryName(fullZipToPath);

                    if (!Directory.Exists(directoryName) || directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    if (entry.IsFile)
                    {
                        if (File.Exists(fullZipToPath) && !overwrite)
                        {
                            continue;
                        }

                        byte[] buffer = new byte[4096];
                        Stream inputStream = archive.GetInputStream(entry);
                        using (FileStream outputStream = new FileStream(fullZipToPath, FileMode.OpenOrCreate,
                                                                     FileAccess.Write, FileShare.Write))
                        {
                            StreamUtils.Copy(inputStream, outputStream, buffer);
                        }
                    }
                }
            }
            finally
            {
                if (archive != null)
                {
                    archive.IsStreamOwner = true;
                    archive.Close();
                }
            }
        }
    }
}
